import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { FoodsDataItem, FoodsListItem } from '@/api' // 类型

export const useFoodStore = defineStore('food', () => {
  interface List {
    title: string
    des: string
    color: string
    min: number
    max: number
    list: FoodsListItem[]
  }

  const foodList = ref<FoodsDataItem[]>([]) // 从接口获取的食物列表
  const selectList = ref<FoodsListItem[]>([]) // 已选中的食物的列表
  const evaluationData = ref<List[]>([
    {
      title: '建议少吃',
      des: '以下食物升糖指数偏高, 建议少吃',
      color: 'red',
      min: 70,
      max: 100,
      list: [],
    },
    {
      title: '适量食用',
      des: '以下食物升糖指数适中, 建议适量食用',
      color: 'orange',
      min: 40,
      max: 70,
      list: [],
    },
    {
      title: '放心食用',
      des: '以下食物升糖指数偏低, 可以放心食用',
      color: 'green',
      min: 0,
      max: 40,
      list: [],
    },
  ])

  // 修改食物列表
  const setFoodList = (list: FoodsDataItem[]) => {
    foodList.value = list
  }
  // 修改已选中食物列表
  const setSelectList = (food: FoodsListItem) => {
    food.checked = !food.checked
    if (food.checked) {
      selectList.value.push(food)
    } else {
      selectList.value = selectList.value.filter((v) => v.name !== food.name)
    }
    setEvaluationData()
  }
  // 从已选食物中筛选对应类型的食物
  const setEvaluationData = () => {
    evaluationData.value.forEach((item) => {
      item.list = selectList.value.filter(
        (v) => +v.glycemicIndex >= item.min && +v.glycemicIndex <= item.max,
      )
    })
  }
  // 查找食物
  const queryFood = (foodName: string): FoodsListItem | undefined => {
    return selectList.value.find((v) => v.name === foodName)
  }

  return {
    foodList,
    setFoodList,
    selectList,
    setSelectList,
    evaluationData,
    queryFood,
  }
})
